/**
 * Author shuqi
 * Rev
 * Date: 2020-01-01 11:00
 * <p>
 * Copyright (C) 2020 Seeyon, Inc. All rights reserved.
 * <p>
 * This software is the proprietary information of Seeyon, Inc.
 * Use is subject to license terms.
 *
 * @company seeyon.com
 * @since V5 V8.0
 * @author shuqi
 */
package com.shuqi.tools;

import com.intellij.ide.util.PropertiesComponent;
import com.intellij.openapi.fileEditor.FileEditorManagerListener;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFileManager;
import com.shuqi.tools.dto.BuildConfig;
import com.shuqi.tools.listeners.FileOpenListener;
import com.shuqi.tools.listeners.SyncFileListener;
import com.shuqi.tools.utils.Constants;
import com.shuqi.tools.utils.LoggerUtils;
import com.shuqi.tools.utils.SyncUtils;
import com.shuqi.utils.JSONUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @date 2020-01-01 11:00
 * @since V5 V8.0
 * @author shuqi
 */
public class CMPHelper {
	private static Map<Project,CMPHelper> cmpHelperMap = new HashMap<>();
	private Project project;
	private BuildConfig config;
	/**
	 * 获取实例
	 * @param project
	 * @return
	 */
	public static CMPHelper getHelper(Project project){
		return cmpHelperMap.get(project);
	}
	public CMPHelper(Project project) {
		LoggerUtils.info("init CMP Helper");
		this.project = project;
		cmpHelperMap.put(project, this);
		// 注册文件变化event
		project.getMessageBus().connect().subscribe(VirtualFileManager.VFS_CHANGES, new SyncFileListener(this));
		project.getMessageBus().connect().subscribe(FileEditorManagerListener.FILE_EDITOR_MANAGER, new FileOpenListener(this));

		// 初始化配置数据
		initConfig();
	}
	public Project getProject() {
		return project;
	}
	/**
	 * 同步文件
	 * @param path
	 * @date	2020-01-01 12:42:47
	 * @since	V5 V8.0
	 * @author  shuqi
	 */
	public void syncFile(String path) {
		try {
			SyncUtils.syncFile(path,this);
		}catch (Exception e){
			LoggerUtils.error("同步文件出错了", e);
		}
	}

	private void initConfig() {
		PropertiesComponent pc = PropertiesComponent.getInstance(project);
		String configjson = pc.getValue(Constants.cmpHelperConfigStoreKey, "{}");
		LoggerUtils.info("loading project config : " +  configjson);
		config = JSONUtils.parseJson(configjson, BuildConfig.class);
	}
	/**
	 * 获取配置信息
	 * @return
	 * @date	2019-12-11 12:59:45
	 * @since	V5 V8.0
	 * @author  shuqi
	 */
	public BuildConfig getConfig() {
		return config;
	}

	/**
	 * 持久化配置信息
	 * @param config
	 * @date	2019-12-11 13:00:07
	 * @since	V5 V8.0
	 * @author  shuqi
	 */
	public void storeConfig(BuildConfig config) {
		PropertiesComponent pc = PropertiesComponent.getInstance(project);
		this.config = config;
		String configjson = JSONUtils.toJson(this.config);
		pc.setValue(Constants.cmpHelperConfigStoreKey, configjson);
		LoggerUtils.info("store project config : " +  configjson);
	}
}
